package servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import usecases.GestionConcoursPizza;
import domaine.ApprentiPizzaiolo;
import domaine.ConcoursPizza;

/**
 * Servlet implementation class SalleDAttente
 */
@WebServlet(name = "salledattente.html")
public class SalleDAttente extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private GestionConcoursPizza gestionConcoursPizza;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getSession().getAttribute("apprenti") == null) {
			response.sendRedirect("index.html");
			return;
		}
		Map<String, ConcoursPizza> lesConcours = (Map<String, ConcoursPizza>) getServletContext()
				.getAttribute("lesConcours");

		Map<String, ConcoursPizza> concoursEnAttente = new HashMap<String, ConcoursPizza>();

		for (Entry<String, ConcoursPizza> e : lesConcours.entrySet()) {
			concoursEnAttente.put(e.getKey(), e.getValue());
		}

		ApprentiPizzaiolo apprenti = null;
		HttpSession session = request.getSession();
		synchronized (session) {
			apprenti = (ApprentiPizzaiolo) session.getAttribute("apprenti");
			System.out.println(apprenti);
			if (session.getAttribute("concoursRejoint") != null) {
				session.removeAttribute("concoursRejoint");
			}

			Map<String, ConcoursPizza> concoursEnPause = new HashMap<String, ConcoursPizza>();
			List<ConcoursPizza> listeConcoursNonFini = gestionConcoursPizza
					.listeConcoursNonFini(apprenti);
			for (ConcoursPizza unConcours : listeConcoursNonFini) {
				concoursEnPause.put(unConcours.getNomConcours(), unConcours);
				concoursEnAttente.remove(unConcours.getNomConcours());
			}
			request.setAttribute("concoursEnPause", concoursEnPause);
			request.setAttribute("concoursEnAttente", concoursEnAttente);
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"SalleDAttente");
			rd.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
